<template>
  <div class="container">
    <div style="position: relative; padding: 0 0 70px 0" class="dark-top">
      <div ref="topDiv" class="c-box">
        <!-- 基础信息部分 -->
        <div class="upload-title-box">
          <div class="upload-title">基础信息</div>
          <div class="switch">
            <!-- <el-switch v-model="openSwitch" @change="changeSwitch" />
            <span style="font-size: 16px; margin: 5px">固定</span>
            <el-input-number
              v-model="inputSwitch"
              :disabled="openSwitch"
              size="mini"
              style="width: 80px"
              controls-position="right"
              :min="1"
              :max="4" />
            <span style="font-size: 16px; margin: 5px">行</span> -->
          </div>
        </div>
        <!-- :is-place="$route.query.showDetail" -->
        <hk-form
          ref="hkFormRef1"
          :top="top"
          :is-fixed="true"
          :form-labels="basicArr"
          :rules="formRules"
          :data="formData"
          :dict-list="dictList"
          :btn-hidden="true"
          :disabled="Boolean($route.query.showDetail)"
          label-width="130"
          @getTop="getTop">
          <template #filter-registeredCapital>
            <el-input v-model="formData.registeredCapital" placeholder="请输入注册资本" :maxlength="20">
              <el-button slot="append">万</el-button>
            </el-input>
          </template>
        </hk-form>
      </div>
      <div class="c-box">
        <!-- <div class="upload-title-box">
          <div class="upload-title">资质情况</div>
        </div> -->
        <div style="display: flex">
          <i
            v-if="showBottom"
            class="el-icon-arrow-down c-box-title"
            style="font-size: 16px"
            @click="showBottom = false" />
          <i
            v-if="!showBottom"
            class="el-icon-arrow-right c-box-title"
            style="font-size: 16px"
            @click="showBottom = true" />
          <div class="c-box-title" style="font-size: 16px; font-weight: 500; margin-left: 5px; margin-bottom: 10px">
            资质情况
          </div>
        </div>
        <el-form ref="form" :model="formData" label-width="120px" label-position="left" style="padding: 0px">
          <el-row v-if="showBottom" style="padding: 0 10px">
            <el-col :span="12">
              <el-form-item class="is-required" prop="eligibility" label="资格条件">
                <el-select
                  v-model="formData.eligibility"
                  multiple
                  placeholder="请选择"
                  :disabled="$route.query.showDetail == '1'"
                  style="width: 100%">
                  <el-option
                    v-for="item in dictList.eligibilityList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item class="is-required" prop="condition" label="资质信息">
                <el-row :gutter="20" class="info-row">
                  <el-col v-for="(i, idx) in formData.credentials" :key="idx" :span="8">
                    <aptitude-info
                      :dict-list="dictList"
                      :detail-obj="i"
                      @handleEdit="handleEdit(i, idx)"
                      @handleDelete="handleDelete(idx)" />
                  </el-col>
                  <el-col v-if="!$route.query.showDetail" :span="8">
                    <div
                      class="add"
                      @click="
                        $refs.addApt.show()
                        $refs.addApt.title = '新增'
                      ">
                      <i class="el-icon-plus" />
                      <p>新增资质信息</p>
                    </div>
                  </el-col>
                </el-row>
                <span v-if="$route.query.showDetail && !formData.credentials.length">暂无信息</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div v-if="$route.query.showDetail" class="c-box">
        <!-- <div class="upload-title-box">
          <div class="upload-title">参与项目情况</div>
        </div> -->
        <div style="display: flex">
          <i
            v-if="showTable"
            class="el-icon-arrow-down c-box-title"
            style="font-size: 16px"
            @click="showTable = !showTable" />
          <i
            v-if="!showTable"
            class="el-icon-arrow-right c-box-title"
            style="font-size: 16px"
            @click="showTable = !showTable" />
          <div
            class="c-box-title"
            style="font-size: 16px; font-weight: 500; margin-left: 5px; margin-bottom: 10px"
            @click="showTable = !showTable">
            参与项目情况
          </div>
        </div>
        <template v-if="showTable">
          <search-form
            class="search-content"
            :data="queryParams"
            :field-list="filterInfo.fieldList"
            :list-type-info="dictList"
            @handleSearch="handleQuery"
            @handleReset="resetQuery" />

          <hk-table
            :table-data="tableData"
            :table-columns="tableList"
            :show-index="true"
            :show-pag="false"
            :loading="loading"
            :table-height="80">
            <template #procureFileName="scope">
              <el-link
                type="primary"
                target="_blank"
                @click="downloadDoc(scope.row.procureFilePath, scope.row.procureFileName)"
                >{{ scope.row.procureFileName }}</el-link
              >
            </template>
            <template #contractFileName="scope">
              <el-link
                type="primary"
                target="_blank"
                @click="downloadDoc(scope.row.contractFilePath, scope.row.contractFileName)"
                >{{ scope.row.contractFileName }}</el-link
              >
            </template>
          </hk-table>
        </template>
      </div>
    </div>
    <footer>
      <div class="div-foot">
        <el-button v-if="!$route.query.showDetail" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </footer>
    <add-aptitude ref="addApt" :dict-list="dictList" @handleSubmit="addMessage" />
  </div>
</template>

<script>
import { downloadDoc } from '../../utils'
import { removeAria } from '@/utils/hongke.js'
import HkForm from '@/components/Hk-Form'
import Treeselect from '@riophae/vue-treeselect'
import AptitudeInfo from './aptitudeInfo.vue'
import addAptitude from './addAptitude.vue'
import SearchForm from '@/components/HkSearchform/index.vue'
import HkTable from '@/components/Hk-Table/index.vue'
import { detail, areaList, listByCode, saveOrUpdate, projectInvolvement } from '@/api/specialProject/unit'
export default {
  components: { HkForm, Treeselect, AptitudeInfo, SearchForm, HkTable, addAptitude },
  // beforeRouteLeave(to, from, next) {
  //   console.log(to, 'ssss')
  //   if (to.path === '/specialProject/unit') {
  //     to.meta.keepAlive = true
  //   }
  //   next()
  // },
  data() {
    return {
      openSwitch: false,
      showBottom: true,
      showTable: true,
      inputSwitch: 2,
      // 表单数据
      formData: {
        credentials: [],
      },

      // 基础信息
      basicArr: [
        {
          label: '单位名称',
          field: 'unitName',
          type: 'input',
          maxlength: 50,
          position: false,
        },
        {
          label: '全国组织机构统一社会信用代码',
          field: 'orgCode',
          type: 'input',
          list: 'secLevelList',
          maxlength: 100,
          position: false,
        },
        {
          label: '单位类型',
          field: 'unitType',
          type: 'select',
          list: 'unitTypeList',
          position: false,
        },
        {
          label: '行政区域',
          field: 'administrative',
          type: 'cascader',
          list: 'provinceList',
          props: {
            checkStrictly: false,
            children: 'children',
            label: 'name',
            value: 'code',
          },

          position: false,
        },
        {
          label: '经营状态',
          field: 'operatingStatus',
          type: 'select',
          list: 'operatingStatusList',
          position: false,
        },
        {
          label: '成立时间',
          field: 'establishmentDate',
          type: 'datePicker',
          format: 'yyyy-MM-dd',
          position: false,
        },
        {
          label: '注册资本',
          field: 'registeredCapital',
          type: 'slot',
          maxlength: 100,
          position: false,
        },
        {
          label: '人员规模',
          field: 'staffSize',
          type: 'input',
          maxlength: 100,
          position: false,
        },
        {
          label: '企业法人',
          field: 'companyLegal',
          type: 'input',
          maxlength: 30,
          position: false,
        },
        {
          label: '注册地址',
          field: 'registeredAddress',
          type: 'input',
          span: 24,
          maxlength: 255,
          position: false,
        },

        {
          label: '企业简介',
          field: 'profile',
          type: 'textarea',
          attrs: {
            rows: '3',
          },
          maxlength: 5000,
          span: 24,
          position: false,
        },
      ],
      id: '',
      // 表单校验
      formRules: {
        unitName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        orgCode: [{ required: true, message: '不能为空', trigger: 'blur' }],
        unitType: [{ required: true, message: '不能为空', trigger: 'change' }],
        administrative: [{ required: true, message: '不能为空', trigger: 'change' }],
        operatingStatus: [{ required: true, message: '不能为空', trigger: 'change' }],
        establishmentDate: [{ required: true, message: '不能为空', trigger: 'change' }],
        registeredCapital: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { pattern: /^(0|[1-9][0-9]*)$/, message: '只能是数字', trigger: 'blur' },
        ],
        staffSize: [
          { required: true, message: '不能为空', trigger: 'blur' },
          // { pattern: /^(0|[1-9][0-9]*)$/, message: '只能是数字', trigger: 'blur' }
        ],
        companyLegal: [
          { required: true, message: '不能为空', trigger: 'blur' },
          //  { validator: this.valuePrice }
        ],
        registeredAddress: [{ required: true, message: '不能为空', trigger: 'blur' }],
        isNum: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字值', trigger: 'blur' },
        ],
      },
      dictList: {
        secLevelList: [],
        unitTypeList: [],
        provinceList: [],
        operatingStatusList: [],
      },
      queryParams: {
        current: 1,
        size: 10,
      },

      tableData: [],
      total: 0,
      loading: false,
      tableList: [
        { label: '项目名称', param: 'projectName' },
        { label: '采购类型', param: 'procureType' },
        { label: '中标时间', param: 'bidderTime' },
        { label: '标包', param: 'name' },
        { label: '采购内容/标的名称', param: 'procureContent' },
        // { label: '关联涉密应用', param: 'applicationName' },
        // { label: '服务人员', param: 'staffSize' },
        { label: '服务周期', param: 'giveDate' },
        { label: '采购合同', param: 'procureFileName', type: 'slot' },
        { label: '服务合同', param: 'contractFileName', type: 'slot' },
        { label: '备注', param: 'notes' },
      ],
      filterInfo: {
        fieldList: [
          {
            label: '',
            type: 'input',
            field: 'keyword',
            placeholder: '请输入项目名称/采购内容',
            maxlength: 20,
          },
          // { label: '', type: 'select', field: 'statusCode', list: 'statusList', placeholder: '请选择项目进展' }
        ],
      },
      top: 0,
    }
  },
  computed: {},

  mounted() {
    this.$nextTick(() => {
      const scrollTop = this.$refs.hkFormRef1.$el.getBoundingClientRect().top

      // 记录元素刚开始的位置
      this.top = scrollTop
      // 记录第一行元素刚开始的位置
      console.log(scrollTop, 'scrollTop')
    })

    this.getTypes()
    this.getForm()
  },
  methods: {
    valuePrice(rule, value, callback) {
      var pattern = /[\\/:*?"<>|.·]/
      if (pattern.test(value)) {
        callback(new Error('不允许输入"·"'))
      } else {
        callback()
      }
    },
    // 表单项重新赋值
    getTop(e) {
      this.basicArr = e
    },
    // 开关固定按钮
    changeSwitch(e) {
      if (e) {
        var scrollTop = this.$refs.formRef.$el.getBoundingClientRect().top
        this.top = scrollTop
        var idx = this.inputSwitch * 2
        this.basicArr.forEach((item, index) => {
          if (index < idx) {
            this.$set(item, 'position', true)
          } else {
            this.$set(item, 'position', false)
          }
        })
      } else {
        this.basicArr.forEach((item, index) => {
          this.$set(item, 'position', false)
        })
      }
    },
    async getForm() {
      await areaList().then((res) => {
        this.dictList.provinceList = res
        this.$nextTick(() => {
          removeAria()
        })
      })
      const id = this.$route.query.id
      this.id = id
      if (id) {
        detail(id).then((res) => {
          this.formData = res
          this.formData.id = id
          this.formData.administrative = [res.provinceCode, res.cityCode, res.areaCode]
        })
      }
      if (this.$route.query.showDetail) {
        this.getDataList({ id })
      }
    },
    getTypes() {
      listByCode('unitType').then((res) => {
        this.dictList.unitTypeList = res.map((i) => {
          return {
            label: i.dictValue,
            value: i.dictKey,
          }
        })
      })

      listByCode('eligibility').then((res) => {
        this.dictList.eligibilityList = res.map((i) => {
          return {
            label: i.dictValue,
            value: i.dictKey,
          }
        })
        this.$forceUpdate()
      })
      listByCode('operatingStatus').then((res) => {
        this.dictList.operatingStatusList = res.map((i) => {
          return {
            label: i.dictValue,
            value: i.dictKey,
          }
        })
      })
      listByCode('credentialLevel').then((res) => {
        this.dictList.credentialLevelList = res.map((i) => {
          return {
            label: i.dictValue,
            value: i.dictKey,
          }
        })
      })
      listByCode('credentialType').then((res) => {
        this.dictList.credentialTypelList = res.map((i) => {
          return {
            label: i.dictValue,
            value: i.dictKey,
          }
        })
      })
    },
    getDataList(query) {
      projectInvolvement({ ...this.queryParams, ...query, id: this.$route.query.id }).then((res) => {
        this.tableData = res
      })
    },
    downloadDoc(url, name) {
      downloadDoc(url, name)
    },
    addMessage(i, idx) {
      if (!idx && idx !== 0) {
        this.formData.credentials.push(i)
      } else {
        this.$set(this.formData.credentials, idx, i)
      }
    },
    handleEdit(i, idx) {
      this.$refs.addApt.title = '编辑'
      this.$refs.addApt.show(i, idx)
    },
    handleDelete(idx) {
      this.formData.credentials.splice(idx, 1)
    },
    handleQuery() {
      this.getDataList()
    },
    //  重置
    resetQuery() {
      this.getDataList()
    },

    // 提交事件
    async submitForm() {
      //  let res = await this.$refs.add_table.submitTable();
      let res = await this.$refs.hkFormRef1.handleFormSubmit('formLabels')
      if (!res.eligibility || res.eligibility.length == 0) {
        this.$message.error('请选择资格条件')
        return
      }
      if (!res.credentials || res.credentials.length == 0) {
        this.$message.error('请添加资质信息')
        return
      }
      const [provinceCode, cityCode, areaCode] = res.administrative
      res = { ...res, provinceCode, cityCode, areaCode }
      let query = JSON.parse(JSON.stringify(res))
      query.eligibility = query.eligibility?.join(',')
      res.credentials.forEach((i, index) => {
        query.credentials[index].credentialType = Array.isArray(i.credentialType)
          ? i.credentialType[0]
          : i.credentialType
      })
      saveOrUpdate(query).then((res) => {
        if (!this.$route.query.id) {
          this.$message.success('新增成功')
        } else this.$message.success('修改成功')
        this.cancel()
        this.$emit('handleAdd')
      })
    },
    // 关闭按钮
    cancel() {
      this.$router.go(-1)
    },
  },
}
</script>

  <style lang="scss" scoped>
.switch {
  height: 40px;
  line-height: 40px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
#app.dark-theme {
  .container {
    background: transparent !important;
  }
  footer {
    background: #0a183e !important;
  }
  .div-foot {
    background: transparent !important;
  }
  .dark-top {
    background: transparent !important;
  }
  .switch {
    background: transparent !important;
    color: #fff;
  }
  .add {
    background: transparent !important;
    color: #fff;
    border: 1px solid #fff;
  }
  .c-box {
    background: rgba(59, 139, 255, 0.1);
  }
  .c-box-title {
    color: #fff;
  }
}
.dark-top {
  background-color: #eef0f5;
  overflow: auto;
}
.search-content ::v-deep .el-input {
  width: 320px;
}
.upload-title-box {
  height: 40px;
  width: 100%;
  padding: 0 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  // border-bottom: 1px solid rgba($color: #000000, $alpha: 8%);

  .upload-title {
    font-size: 16px;
    font-weight: 700;
    color: #000000;
  }
}
.container {
  padding: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #eef0f5;
  // overflow: auto;
}
.c-box {
  background: #fff;
  border-radius: 4px;
  padding: 20px;

  margin-bottom: 20px;
}
.el-form {
  flex: 1;
  // overflow: auto;

  // height: 10vh;
}
footer {
  position: fixed;
  bottom: 0;
  right: 20px;
  height: 70px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;

  z-index: 99;
  .div-foot {
    padding: 20px;
    height: 70px;
    line-height: 70px;
    width: 100%;
    // width: calc(100% - 240px);
    display: flex;
    align-items: center;
    justify-content: flex-end;
    background: #fff;
  }
}
.add {
  width: 100%;
  height: 100%;
  min-height: 280px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #fafafa;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  cursor: pointer;
  i {
    font-size: 32px;
  }
  p {
    margin-top: 10px;
  }
}
.info-row {
  display: flex;
  flex-wrap: wrap;
  align-items: stretch;
  .el-col {
    margin-bottom: 20px;
  }
}
::v-deep {
  .el-input-group__append {
    background: transparent;
  }
  .content {
    width: 100%;
    justify-content: flex-end;
    // margin: -20px 0;
  }
}
</style>

